package chuangyi.com.org.ViewModel;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.databinding.Bindable;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;

import com.alipay.sdk.app.PayTask;
import com.tencent.mm.sdk.modelpay.PayReq;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.WXAPIFactory;

import java.util.Map;

import chuangyi.com.org.DOMIHome.BR;
import chuangyi.com.org.DOMIHome.PayResult;
import chuangyi.com.org.DOMIHome.PopupActivity;
import chuangyi.com.org.DOMIHome.R;
import chuangyi.com.org.DOMIHome.WxPayInfoModel;
import chuangyi.com.org.DOMIHome.adapter.ListBindingAdapter;

/**
 * Created by zxh on 16/12/9.
 */

public class PayModel extends ContextObservable {
//    APP ID 1105656299
//    APP KEY gOBK8swGBnfLTpra 安卓QQ分享

    //支付宝付款
    public static final int PAY_ALI = 0;
    // 微信付款
    public static final int PAY_WX = 1;
    // 积分支付
    public static final int PAY_SCORE = 2;

    public static final String APP_ID = "dbdab68994b3e0cb55b8fac6270024f8";

    private String title;

//    @SuppressLint("HandlerLeak")
//    private static Handler mHandler = new Handler() {
//        @SuppressWarnings("unused")
//        public void handleMessage(Message msg) {
//            switch (msg.what) {
//                case 1: {
//                    @SuppressWarnings("unchecked")
//                    PayResult payResult = new PayResult((Map<String, String>) msg.obj);
//                    /**
//                     对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。
//                     */
//                    String resultInfo = payResult.getResult();// 同步返回需要验证的信息
//                    String resultStatus = payResult.getResultStatus();
//                    // 判断resultStatus 为9000则代表支付成功
//                    if (TextUtils.equals(resultStatus, "9000")) {
//                        // 该笔订单是否真实支付成功，需要依赖服务端的异步通知。
//                    } else {
//                        // 该笔订单真实的支付结果，需要依赖服务端的异步通知。
//                    }
//                    break;
//                }
//
//            }
//        }
//
//        ;
//    };

    public interface Callback {
        boolean onPay(PayItem item);
    }

    public interface ResultCallback {
        void onSuccess();

        void onCancel();

        void onError();
    }

    private double amount;
    private ListBindingAdapter<PayItem> payType;
    private Callback payCallback;
//    private ResultCallback mResultCallback;

//    public void setResultCallback(ResultCallback resultCallback) {
//        this.mResultCallback = resultCallback;
//    }

    @Bindable
    public double getAmount() {
        return amount;
    }

    public void setAmount(double amount) {
        this.amount = amount;
    }

    @Bindable
    public ListBindingAdapter<PayItem> getPayType() {
        return payType;
    }

    @Bindable
    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    @Override
    public void setContext(Context context) {
        super.setContext(context);
    }

    /**
     * 用户选则支付方式后回掉
     *
     * @param payCallback
     */
    public void setPayCallback(Callback payCallback) {
        this.payCallback = payCallback;
    }

    public PayModel(Context context, double amount) {
        super(context);
        payType = new ListBindingAdapter<PayItem>(getContext(), BR.payItem);
        initPayType();
        this.amount = amount;
    }

    private void initPayType() {
        PayItem payItem = new PayItem(getContext(), R.layout.i_pay_item);
        payItem.setName("支付宝");
        payItem.setSrc(R.mipmap.ali_pay);
        payItem.setType(PAY_ALI);
        payItem.setParent(this);
        payType.add(payItem);

        payItem = new PayItem(getContext(), R.layout.i_pay_item);
        payItem.setName("微信");
        payItem.setSrc(R.mipmap.wx_pay);
        payItem.setType(PAY_WX);
        payItem.setParent(this);
        payType.add(payItem);
    }

    public void addScorePay() {
        PayItem payItem = new PayItem(getContext(), R.layout.i_pay_item);
        payItem.setName("积分");
        payItem.setSrc(R.mipmap.jifen);
        payItem.setType(PAY_SCORE);
        payItem.setParent(this);
        payType.add(payItem);
    }

    public void onClickCancel(View view) {
        Activity activity = (Activity) getContext();
        activity.setResult(Activity.RESULT_CANCELED);
        activity.finish();
    }

    public void onPay(PayItem item) {
        if (payCallback != null) {
            payCallback.onPay(item);
        }
//        wxModel = model.getWxpayInfo();
////						wxPayDate();
//        Intent intent  = new Intent(context, WXPayEntryActivity.class);
//        intent.putExtra(Constant.WX_TYPE, 2);
//        Bundle bundle = new Bundle();
//        bundle.putSerializable(Constant.WX_ORDER_INFOR, wxModel);
//        intent.putExtras(bundle);
//        context.startActivity(intent);
    }

    public void callPay(PayItem payItem) {
        if (payItem.getType() == PAY_WX) {
            WxPayInfoModel wxModel = (WxPayInfoModel) payItem.getPayData();

            IWXAPI api = WXAPIFactory.createWXAPI(getContext(), null);
            api.registerApp(wxModel.getAppid());

            PayReq req = new PayReq();
            //req.appId = "wxf8b4f85f3a794e77";  // 测试用appId
            req.appId = wxModel.getAppid();
            req.partnerId = wxModel.getPartnerid();
            req.prepayId = wxModel.getPrepayid();
            req.nonceStr = wxModel.getNoncestr();
            req.timeStamp = wxModel.getTimestamp();
            req.packageValue = wxModel.getPackage();
            req.sign = wxModel.getSign();
            req.extData = "app data"; // optional
            // 在支付之前，如果应用没有注册到微信，应该先调用IWXMsg.registerApp将应用注册到微信
            api.sendReq(req);


        } else if (payItem.getType() == PAY_ALI) {
            alipayDate((String) payItem.getPayData());
        } else {

        }
    }

    /**
     * 调用支付宝
     */
    public void alipayDate(final String orderInfo) {

        Runnable payRunnable = new Runnable() {

            @Override
            public void run() {
                PayTask alipay = new PayTask((Activity) getContext());
                final Map<String, String> result = alipay.payV2(orderInfo, true);
                Log.i("msp", result.toString());

                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        PayResult payResult = new PayResult(result);
                        /**
                         对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。
                         */
                        String resultInfo = payResult.getResult();// 同步返回需要验证的信息
                        String resultStatus = payResult.getResultStatus();
                        // 判断resultStatus 为9000则代表支付成功
                        if (TextUtils.equals(resultStatus, "9000")) {
                            notifyPayResult(true);
                            // 该笔订单是否真实支付成功，需要依赖服务端的异步通知。
                        } else if (TextUtils.equals(resultStatus, "4000")) {
                            showToast("请安装支付宝客户端");
                        } else {
                            // 该笔订单真实的支付结果，需要依赖服务端的异步通知。
                        }
                    }
                });
            }
        };

        Thread payThread = new Thread(payRunnable);
        payThread.start();
    }

    public void notifyPayResult(Boolean success) {
        if (success == null || success) {
            if(success != null && success){
                showToast("支付成功");
            }
            Activity activity = (Activity) getContext();
            activity.setResult(success == null ? Activity.RESULT_CANCELED : Activity.RESULT_OK);
            activity.finish();
        }
    }
}
